from machine import Pin, SPI, PWM, WDT
import socket
import time
import network
import machine
import re

wdt = WDT(timeout=10000)
led = Pin(2, Pin.OUT)

def door():
    led.value(1)
    p2 = PWM(Pin(12))
    p2.freq(50)
    p2.duty_u16(6800)
    time.sleep(0.5)
    p2.duty_u16(2000)
    time.sleep(2)
    p2.duty_u16(6800)
    time.sleep(0.5)
    print('开门')
    p2.deinit()
    
def flight():
    led.value(0)
    p1 = PWM(Pin(33))
    p1.freq(50)
    p1.duty_u16(4915)  # 停
    p1.duty_u16(3932)  # 顺时针
    time.sleep_ms(550)        
    p1.duty_u16(4915)  # 停
    time.sleep(0.5)
    print('关灯')
    p1.deinit()
    
def do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('303', '303303303')
        i = 1
        while not wlan.isconnected():
            print("正在链接...{}".format(i))
            i += 1
            time.sleep(1)
    print('network config:', wlan.ifconfig())
    return wlan.ifconfig()[0]

def handle_request(client_socket):  
    # 1. 接收
    recv_content = client_socket.recv(1024).decode("utf-8")
    lines = recv_content.splitlines()  # 将接收到的http的request请求数据按照行进行切割到一个列表中
    request_file_path = re.match(r"[^/]+(/[^ ]*)", lines[0]).group(1)
    print("----提出来的请求路径是：----")
    print(request_file_path)
    print("test---1---")
    # 完善对方访问主页的情况，如果只有/那么就认为浏览器要访问的是主页
    if request_file_path == "/":
        request_file_path = "opendoor.html"
        door()
    elif request_file_path == "/switch_off":
        request_file_path = "opendoor.html"
        flight() 
    try:
        # 取出对应的文件的数据内容
        with open(request_file_path, "rb") as f:
            content = f.read()
    except Exception as ret:
#         door()
        request_file_path = "opendoor.html"
        time.sleep(10)
        print("test---5---")
    else:
        # 如果要是没有异常，那么就认为：找到了指定的文件，将其数据回送给浏览器即可
        response_headers = "HTTP/1.1 200 OK\r\n"
        response_headers += "Connection: close\r\n"
        response_headers += "Content-Type:text/html;charset=utf-8\r\n"
        response_headers += "\r\n"
        response_boy = content
        response = response_headers.encode("utf-8") + response_boy
        # 3.2 给浏览器回送对应的数据
        client_socket.send(response)
        print("test---6---")

    # 4. 关闭套接字
    client_socket.close()
    print("test---7---")

def tcp_server_control_led():
    print("---1---")
    # 1. 创建套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 为了保证在tcp先断开的情况下，下一次依然能够使用指定的端口，需要设置
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    print("---2---")
    # 2. 绑定本地信息
    tcp_server_socket.bind(("", 80))
    print("---3---")
    tcp_server_socket.listen(128)
    print("---4---")
    while True:
        # 4. 等待客户端的链接
        client_socket, client_info = tcp_server_socket.accept()
        print("---5---")
        print(client_info)  # 打印 当前是哪个客户端进行了请求
        print("---6---")
        wdt.feed()
        # 5. 为客户端服务
        try:
            handle_request(client_socket)
        except Exception as ret:
            print("error:", ret)
            request_file_path = "opendoor.html"
            time.sleep(10)
#             break
    print("---7---")
    # 6. 关闭套接字
    tcp_server_socket.close()

def main():
    # 1. 链接wifi
    ip = do_connect()
    print("ip地址是：", ip)
    # 3. 创建tcp服务器，等待客户端链接，然后根据客户端的命令控制LED灯
    tcp_server_control_led()   
    
if __name__ == "__main__":
    main()
